﻿package com.gobang.util.uipattern;

import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

public class DesktopCapture {

	CaptureView view;
	BufferedImage desktopImg;
	BufferedImage captureImg = null;
	String captureImgPath = null;

	public DesktopCapture() {
		capture();
	}

	public BufferedImage getCaptureImg() {
		return captureImg;
	}

	public String getCaptureImgPath() {
		if (captureImg != null) {
			return captureImgPath;
		} else {
			return null;
		}
	}

	//获得屏幕图片
	public void captureDesktop() throws Exception{
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		Rectangle rect = new Rectangle(d);
		desktopImg = new BufferedImage((int)d.getWidth(),(int)d.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);
		GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
		GraphicsDevice device = environment.getDefaultScreenDevice();
		Robot robot = new Robot(device);
		desktopImg = robot.createScreenCapture(rect);
	}

	//截图
	public void capture(){

		try {
			captureDesktop();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		if(view == null){
			view = new CaptureView(this, desktopImg);
		}else{
			view.refreshBackGround(desktopImg);
		}
	}

	//保存截图
	public void saveCapture(int x1 , int y1 ,int x2 , int y2){
		if (Math.abs(x2-x1) < 1 || Math.abs(y2-y1) < 1) {
			return;
		}
		captureImg = desktopImg.getSubimage(x1, y1, Math.abs(x2-x1), Math.abs(y2-y1));
		int randomNumber = Math.abs((int)(Math.random()*10000000));
		String folder=System.getProperty("java.io.tmpdir");
		captureImgPath = folder + "gobangtemp\\" + randomNumber + ".jpg";
		captureToFile(desktopImg.getSubimage(x1, y1, Math.abs(x2-x1), Math.abs(y2-y1)), 
				"jpg",new File(captureImgPath));
	}

	//截图输出到文件
	public void captureToFile(BufferedImage img , String endWith , File file){
		if(!file.exists()){
			file.mkdirs();
		}
		try {
			ImageIO.write(img, endWith, file);
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "截图保存出错...");
			e.printStackTrace();
		}
	}

	//	public static void main(String[] args) {
	//		DesktopCapture desk = new DesktopCapture();
	//	}

}
